package weeny.util;

import java.util.*;

/**
 * A simple biMap collection. Do not know why java lib refuse to provide...
 * 
 * @author weeny
 *
 * @param <K> key type
 * @param <V> value type
 */
public class BiMap<K,V> {

    private HashMap<K,V> keyVal;
    private HashMap<V,K> valKey;
    
    public BiMap(){
    	keyVal = new HashMap<K, V>();
    	valKey = new HashMap<V, K>();
    }

    public void clear(){
    	keyVal = new HashMap<K, V>();
    	valKey = new HashMap<V, K>();
    }
    public int size(){
    	return keyVal.size();
    }
    public void put(K key, V val){
        if (keyVal.containsKey(key)) {
			throw new IllegalArgumentException
			("the key "+key+" is already in the map");
		}
        if (valKey.containsKey(val)) {
        	throw new IllegalArgumentException
        	("the value "+val+" is already in the map");
        }
        keyVal.put(key, val);
        valKey.put(val, key);
    }
    
    public V removeKey(K key){
    	V value = getVal(key);
    	keyVal.remove(key);
    	if (value != null) {
			valKey.remove(value);
		}
    	return value;
    }
    public K removeVal(V val){
    	K key = getKey(val);
    	valKey.remove(val);
    	if (key != null) {
    		keyVal.remove(key);
		}
    	return key;
    }
    public K getKey(V val){
        return valKey.get(val);
    }

    public V getVal(K key){
        return keyVal.get(key);
    }

    public boolean containsKey(K key){
        return keyVal.containsKey(key);
    }
    
    public boolean containsVal(V val){
        return valKey.containsKey(val);
    }
}
